package me.fenglu.autodeploy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class FileClassifier {
	public static String rootPath = "";
	
	static{
		rootPath = FileClassifier.class.getClassLoader().getResource("").getPath();
		rootPath = rootPath.substring(0, rootPath.length() - "target/classes/".length()) + "code/";
	}
	
	public static void classify(String gitProjPath, List<Map<String, Object>> files) {
		
		for(Map<String, Object> fileEntry : files) {
			String changeType = (String)fileEntry.get("changeType");
			String filePath = (String) fileEntry.get("filePath");
			String fileType = (String) fileEntry.get("fileType");
			
			String sourceFilePath = gitProjPath;
			String targetFilePath = rootPath;
			if(!changeType.equals("delete")) {
				switch (fileType) {
				case "java":
					sourceFilePath = sourceFilePath+"/build/"+"classes/";
					filePath = filePath.substring("src/".length(), filePath.lastIndexOf("."));
					sourceFilePath = sourceFilePath + filePath + ".class";
					targetFilePath += "WEB-INF/classes/" + filePath + ".class";
					break;
				default:
					sourceFilePath = sourceFilePath + filePath;
					targetFilePath += filePath.substring("WebContent/".length());
					break;
				}
			}
			
			BufferedInputStream bis = null;
			FileInputStream fis = null;
			byte[] buffer = null;
			
			BufferedOutputStream bos = null;
			FileOutputStream fos = null;
			try {
				buffer = new byte[102400];
				fis = new FileInputStream(new File(sourceFilePath));
				bis = new BufferedInputStream(fis);
				
				File targetFile = new File(targetFilePath);
				if(!targetFile.exists()) {
					targetFile = new File(targetFilePath.substring(0, targetFilePath.lastIndexOf("/")));
					targetFile.mkdirs();
				}
				fos = new FileOutputStream(targetFilePath);
				bos = new BufferedOutputStream(fos); 
				int len = 0;
				while((len = bis.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
					bos.flush();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					if(null != bis) {
						bis.close();
					}
					if(null != fis) {
						fis.close();
					}
					if(null != bos) {
						bos.close();
					}
					if(null != fos) {
						fos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
	}
}
